//
//  ApiHelper.m
//  uneed
//
//  Created by apple on 3/23/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "ApiHelper.h"
//#import "Log.h"

static NSString * const BOUNDRY        = @"--------------------------7d71a819230404";


@interface ApiHelper(Private) 


@end


@implementation  ApiHelper(Private) 


- (void)connection:(NSURLConnection *)connection   
  didFailWithError:(NSError *)error            {
//    CMLog(@"NSURLCOnnection ERROR!");
	NSArray *ret_arr = [NSArray arrayWithObjects:mIndex,error,nil];
//	NSString *_ret_str = [NSString stringWithFormat:@"%@",[ret_arr JSONString]];
	
	self.connection = nil;
	[mdelegate performSelector: doneSelector  withObject:ret_arr];
}

- (void)connection:(NSURLConnection *)connection     
	didReceiveData:(NSData *)data              {
// 	CMLog(@"NSURLConnection ReceivedData!");
	[self.reply appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
    NSDictionary *fields = [HTTPResponse allHeaderFields];
	NSLog(@"response头内容＝＝＝%@",[fields description]);
    NSString *cookie = [fields valueForKey:@"Set-Cookie"]; // It is your cookie
	if ([cookie length]>0) {
		[[NSUserDefaults standardUserDefaults] setObject:cookie forKey:@"cookies"];
	}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Set appIcon and clear temporary data/image
    NSString *ret_str = [[NSString alloc] initWithData:self.reply encoding:NSUTF8StringEncoding];
	NSArray *ret_arr = [NSArray arrayWithObjects:mIndex,ret_str,nil];
	
    // call our delegate and tell it that our icon is ready for display
//	NSString *_ret_str = [NSString stringWithFormat:@"%@",[ret_arr JSONString]];
	self.connection = nil;
	
	[mdelegate performSelector:doneSelector  withObject:ret_arr];
//    [mdelegate appImageDidLoad:self.indexPathInTableView];
}


@end


@implementation ApiHelper

@synthesize reply,connection,mIndex;

-(void)cancelApi {
	[connection cancel];
    self.connection = nil;
	mdelegate = nil;    
}

-(id)  initWithUrl:(NSString*) urlPath 
		  postData:(NSDictionary*)  data
		  delegate:(id)  aDeletgate
		 withIndex:(NSString *) theIndex
onCompletedCallback:(SEL) complectedCallback
{
    [self cancelApi];
	if (self=[super init]) {
		requestUrlPath =[[NSString stringWithString:  urlPath] lowercaseString] ;
        reply = [[NSMutableData alloc]init];
		mdelegate=[  aDeletgate retain];
		self.mIndex = theIndex;
		doneSelector = complectedCallback ;
		NSURL  * url=[NSURL URLWithString:requestUrlPath] ;
		NSMutableURLRequest  * req=[NSMutableURLRequest requestWithURL: url];
		if (data != nil ) {
			
			[req setHTTPMethod:@"POST"];
			
			NSString *_cookies = [[NSUserDefaults standardUserDefaults] objectForKey:@"cookies"];
			if ([_cookies length]>0) {
				[req addValue:_cookies forHTTPHeaderField:@"Set-Cookie"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello"
                                                                message:[NSString stringWithFormat:@"Order: %@", _cookies ]
                                                               delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
			}
			
			[req setValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BOUNDRY]
	   forHTTPHeaderField:@"Content-Type"];
			int len=512;
			NSMutableData  * postData =[NSMutableData dataWithCapacity:len];
		//	NSMutableData  * postData =[NSMutableData data];
			[postData  appendData: [[NSString  stringWithFormat:@"--%@\r\n",BOUNDRY] 
									dataUsingEncoding:NSUTF8StringEncoding]];
			int  i=0;
			int  cnt=data.count ;

//			[postData  appendData: [[NSString  stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"Cookie" ] 
//									dataUsingEncoding:NSUTF8StringEncoding]];
//			[postData  appendData: [[NSString  stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"cookies"]] 
//									dataUsingEncoding:NSUTF8StringEncoding]];
//			
//			[postData  appendData: [[NSString  stringWithFormat:@"\r\n--%@\r\n",BOUNDRY] 
//									dataUsingEncoding:NSUTF8StringEncoding]];

			for ( NSString * key in  [data allKeys]) 
			{
				[postData  appendData: [[NSString  stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key ] 
										dataUsingEncoding:NSUTF8StringEncoding]];
				[postData  appendData: [[NSString  stringWithFormat:@"%@",[data objectForKey:key ]] 
										dataUsingEncoding:NSUTF8StringEncoding]];
				if( i != cnt -1  ){
					[postData  appendData: [[NSString  stringWithFormat:@"\r\n--%@\r\n",BOUNDRY] 
											dataUsingEncoding:NSUTF8StringEncoding]];
				}
				i++ ;
			}
			
			[postData  appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",BOUNDRY]
								   dataUsingEncoding:NSUTF8StringEncoding]];
			[req  setHTTPBody:postData];
		}
		else {
			[req  setHTTPMethod:@"GET"];
		}
		
		NSURLConnection *_connection =[[NSURLConnection alloc] initWithRequest:req delegate:self];
		self.connection = _connection;
		[_connection release];
		if(!connection){ 
			NSDictionary * errorInfo=[NSDictionary dictionaryWithObjectsAndKeys:@"发送请求失败" ,@"errorKey", nil];
			NSError * error=[NSError  errorWithDomain:@"www.mainaer.com" code:100 userInfo:  errorInfo];
			NSArray *ret_arr = [NSArray arrayWithObjects:mIndex,error,nil];
//			NSString *_ret_str = [NSString stringWithFormat:@"%@",[ret_arr JSONString]];
			[mdelegate performSelector:complectedCallback withObject:ret_arr];
			self.connection = nil;
		}  else {
//			CMLog(@"Send Data Request \n");
		}
		
	}
	return self ;
}


- (void)dealloc
{
	[connection cancel];
	[reply release];
    [mdelegate release];
	mdelegate = nil;
	
    doneSelector = NULL;
    [super dealloc];
}


@end
